package com.zzyl.nursing.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.node.POJONode;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WechatService {
    private static final String OPEMID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${weixin.appid}")
    public String appid;
    @Value("${weixin.appsecret}")
    public String appsecret;

    @Override
    public String getOpenid(String code) {
        //1. 组装参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",appsecret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //2. 发送请求获取结果
        String result = HttpUtil.get(OPEMID_URL,map);
        //把json形式的结果转为通用对象
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode")==null || jsonObject.getInt("errcode")==0){
            //3. 解析结果取出openid
            return jsonObject.getStr("openid");
        }else {
            throw new RuntimeException("获取openid失败"+result);
        }
    }

    @Override
    public String getPhone(String detailCode) {
        //1. 组装参数 token code openid
        String token = getToken();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",detailCode);
        //2. 发送请求，获取返回值
        String result = HttpUtil.post(PHONE_URL+token, JSONUtil.toJsonStr(map));
        // 3. 解析返回值取出手机号
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode")==null || jsonObject.getInt("errcode")==0){
            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            return phoneInfo.getStr("phoneNumber");
        }else {
            throw new RuntimeException("获取openid失败"+result);
        }

    }
    private String getToken(){
        //1. 组装参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid",appid);
        map.put("secret",appsecret);
        //2. 发送请求,获取返回值
        String result = HttpUtil.get(TOKEN_URL, map);
        //3. 解析返回值取出token
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String token = jsonObject.getStr("access_token");
        return token;
    }
}
